package com.bfsuol.bfsuolframework.core.interceptor;

import com.bfsuol.bfsuolframework.core.BfsuolConstants;
import com.bfsuol.bfsuolframework.core.configuration.ConfigUtils;
import com.bfsuol.bfsuolframework.core.controller.LoginInfo;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor  {

	protected final Logger logger = Logger.getLogger(getClass());
	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		LoginInfo loginInfo = (LoginInfo)request.getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		if(loginInfo == null && handler instanceof HandlerMethod){
			String login_url = ConfigUtils.get(BfsuolConstants.CONFIG_LOGIN_URL, request.getContextPath()+"/index/index") ;
			response.sendRedirect(login_url);
			if(logger.isDebugEnabled()){
				logger.debug("用户没有登录，重定向到网站根目录！");
			}
			return false;
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}   

}